package com.ycg.biquge.common;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.nio.charset.StandardCharsets;

/**
 * @author YCG
 * @date 2024-05-15 14:53
 * @description 统一压缩返回结果处理
 */
@ControllerAdvice
public class CompressResult implements ResponseBodyAdvice<Result<Object>> {


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }


    @Override
    public Result<Object> beforeBodyWrite(Result<Object> body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        assert body != null;
        Object data = body.getData();
        if (ObjectUtil.isNull(data)) return body;
        // 设置日期格式
        JSONConfig config = new JSONConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        byte[] bytes = JSONUtil.toJsonStr(data,config).getBytes(StandardCharsets.UTF_8);
        byte[] gzip = ZipUtil.gzip(bytes);
        // spring会自动封装成base64
        body.setData(gzip);

        return body;
    }
}
